package com.sure.supermarketserver.branch.staff;

import com.sure.supermarketserver.common.CommonService;
import com.sure.supermarketserver.common.CurrentUser;
import com.sure.supermarketserver.common.Result;
import com.sure.supermarketserver.common.TokenUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.Map;
import java.util.UUID;

@Slf4j
@RestController//说明这是一个受spring容器管理的控制器组件(Bean)
@RequestMapping("/branch/staff")//说明本控制器内的所有路径都以/branch/staff开头
public class StaffAPI {
    @Resource
    private CommonService commonService;

    @Resource//表示从容器中引入依赖对象
    private StaffService staffService;

    @GetMapping("")//该api接口路径：/branch/staff
    public Result staffList(StaffDto dto, @RequestHeader("Token") String token) {
        //dto会自动按照属性与参数名匹配的规则自动接收

        CurrentUser currentUser = TokenUtils.getUserInfo(token, commonService);
        String userId = currentUser.getUserId();

        boolean ok = staffService.checkStaffList(userId);

        if (ok) {
            Map<String, Object> page = staffService.getStaffList(dto, userId);
            return Result.success(page);

        } else {
            Map<String, Object> page = staffService.getAllStaffList(dto);
            return Result.success(page);

        }
    }

    @RequestMapping("")
    public Result staffAdd(@RequestBody StaffDto dto, @RequestHeader("Token") String token) {
        CurrentUser currentUser = TokenUtils.getUserInfo(token, commonService);
        String userId = currentUser.getUserId();
        try {
            staffService.addStaff(dto, userId);
        } catch (Exception e) {
            return Result.fail(Result.ERR_CODE_BUSINESS, e.getMessage());
        }
        return Result.success();
    }

    @PutMapping("")
    public Result staffUpd(@RequestBody StaffDto dto) {
        staffService.updStaff(dto);
        return Result.success();
    }

    @DeleteMapping("/{id}")
    public Result staffDel(@PathVariable String id) {
        try {
            staffService.delStaff(id);
        } catch (Exception e) {
            return Result.fail(Result.ERR_CODE_BUSINESS, e.getMessage());
        }
        return Result.success();
    }
}
